package com.edu.study.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.study.base.wordBook.domain.WordBook;
import com.edu.study.base.wordBook.service.IWordBookService;
import com.edu.study.base.wordLibrary.domain.wordLibrary;
import com.edu.study.base.wordLibrary.service.IwordLibraryService;
import com.edu.study.base.wordrelation.domain.WordRelation;
import com.edu.study.base.wordrelation.service.IWordRelationService;
import com.edu.study.entities.po.EduWordLibrary;
import com.edu.study.mapper.StuStudyProcessMapper;
import com.edu.study.service.EduWordLearnNewService;
import com.edu.study.service.EduWordService;
import com.edu.study.service.StuStudyProcessService;
import com.edu.utils.UserContextUtil;
import com.ruoyi.common.core.domain.model.AppLoginUser;
import com.edu.study.entities.po.EduWordLearnNew;
import com.edu.study.entities.po.StuStudyProcess;
import com.edu.study.entities.vo.WordCardVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StuStudyProcessServiceImpl extends ServiceImpl<StuStudyProcessMapper, StuStudyProcess> implements StuStudyProcessService {

    @Autowired
    private EduWordLearnNewService eduWordLearnNewService;

    @Autowired
    private IwordLibraryService wordLibraryService;

    @Autowired
    private IWordBookService wordBookService;

    // 基于当前登录用户，获取用户进度信息
    public StuStudyProcess getCurrentUserStudyProcess() {
        AppLoginUser user = UserContextUtil.currentUser();
        List<StuStudyProcess> isExist = this.list(new LambdaQueryWrapper<StuStudyProcess>()
                .eq(StuStudyProcess::getMemberId, user.getId())
        );
        if (CollectionUtil.isEmpty(isExist)) {
            // 新建一条
            StuStudyProcess po = new StuStudyProcess();
            po.setMemberId(user.getId());
            po.setAppLastEnterTime(new Date());
            this.save(po);
            return po;
        }

        return isExist.get(0);
    }

    @Override
    public void updateLastVisitTime() {
        StuStudyProcess po = this.getCurrentUserStudyProcess();
        po.setAppLastEnterTime(new Date());
        this.updateById(po);
    }

    @Override
    public void updateCardMission(WordCardVO wordCardVO) {

        StuStudyProcess po = this.getCurrentUserStudyProcess();

        StuStudyProcess todoUpdatePo = new StuStudyProcess();

        todoUpdatePo.setId(po.getId());

        if (wordCardVO.getSource() == '1') {
            // 更新任务数量
            if (!ObjectUtils.isEmpty(wordCardVO.getWordsMissionNum())) {
                todoUpdatePo.setCourseWordsMissionNum(wordCardVO.getWordsMissionNum());
            }
            // 更新今日任务完成数量
            if (!ObjectUtils.isEmpty(wordCardVO.getTodayWordsMissionCompletedNum())) {
                todoUpdatePo.setCourseWordsLearnedNum(wordCardVO.getTodayWordsMissionCompletedNum());
            }
        } else if (wordCardVO.getSource() == '2') {
            // 更新任务数量
            if (!ObjectUtils.isEmpty(wordCardVO.getWordsMissionNum())) {
                todoUpdatePo.setLevelWordsMissionNum(wordCardVO.getWordsMissionNum());
            }
            // 更新今日任务完成数量
            if (!ObjectUtils.isEmpty(wordCardVO.getTodayWordsMissionCompletedNum())) {
                todoUpdatePo.setLevelWordsLearnedNum(wordCardVO.getTodayWordsMissionCompletedNum());
            }
            todoUpdatePo.setBookId(Long.parseLong(wordCardVO.getBookOrCourseId()));
        }

        this.updateById(todoUpdatePo);
    }

    @Override
    public void updateWordBook(long wordBookId) {
        StuStudyProcess po = this.getCurrentUserStudyProcess();
        po.setBookId(wordBookId);
        this.updateById(po);
    }

    @Override
    public void updateCourse(String courseId) {
        StuStudyProcess po = this.getCurrentUserStudyProcess();
        po.setCourseId(courseId);
        // 更新课程时，顺便更新最近课程访问时间
        po.setCourseLastEnterTime(new Date());
        this.updateById(po);

        // 将课程中的生词添加到生词本 edu_word_learn
        QueryWrapper<EduWordLearnNew> wordLearnQueryWrapper = new QueryWrapper<>();
        wordLearnQueryWrapper
                .eq("member_id", po.getMemberId())
                .eq("word_source", "1")
                .eq("word_sourceID", courseId);

        int wordLearnExists = eduWordLearnNewService.count(wordLearnQueryWrapper);
        // 1. 若课程id是当前用户正在学习的课程，且生词本中存在，则不添加
        if (wordLearnExists > 0) {
            return;
        }

        // 2. 否则，则获取当前课程中的全部生词，添加到生词本中
        wordLibrary wl = new wordLibrary();
        wl.setCourseId(courseId);
        wl.setMemberId(po.getMemberId());
        List<wordLibrary> wordList = wordLibraryService.selectCourseWord(wl);

        if (ObjectUtils.isEmpty(wordList)) {
            // 没找到课程生词
            return;
        }

        List<EduWordLearnNew> wordLearnList = new ArrayList<>();
        for (wordLibrary wordLibrary : wordList) {
            EduWordLearnNew wordLearn = new EduWordLearnNew();
            // 单词来源1：课文
            wordLearn.setWordSource("1");
            // 课程ID
            wordLearn.setWordSourceID(courseId);
            // 用户ID
            wordLearn.setMemberId(po.getMemberId());
            wordLearn.setKo(0); // 0：未ko过，同时也记录ko次数
            wordLearn.setCreateDate(new Date());
            wordLearn.setCreateBy(po.getMemberId());
            wordLearn.setWordId(wordLibrary.getId());
            wordLearnList.add(wordLearn);
        }
        eduWordLearnNewService.saveBatch(wordLearnList);
    }

    @Override
    public void updateLastWordTime() {
        StuStudyProcess po = this.getCurrentUserStudyProcess();
        po.setWordLastReciteTime(new Date());
        this.updateById(po);
    }

    @Override
    public void updateLastCourseTime() {
        StuStudyProcess po = this.getCurrentUserStudyProcess();
        po.setCourseLastEnterTime(new Date());
        this.updateById(po);
    }

    @Autowired
    private IWordRelationService wordRelationService;
    @Autowired
    private EduWordService eduWordService;

    @Override
    public WordCardVO getWordBookCardInfo(String source) {

        if (source == null || !source.equals("1") && !source.equals("2")) {
            return null;
        }
        Date date = DateUtil.date();

        WordCardVO vo = new WordCardVO();
        // 获取用户学习进度信息
        StuStudyProcess process = this.getCurrentUserStudyProcess();

        // 获取所有单词
        List<EduWordLearnNew> learnWords = eduWordLearnNewService.list(new LambdaQueryWrapper<EduWordLearnNew>()
                .eq(EduWordLearnNew::getMemberId, process.getMemberId())
        );

        List<EduWordLearnNew> words = new ArrayList<>();
        WordBook book = new WordBook();
        int wordCount = 0;
        int today = 0; // 今日完成数
        int total = 0; // 总完成数

        if (source.equals("1")) {
            // 获取所有单词
            words = learnWords.stream().filter(i -> i.getWordSource().equals("1")).collect(Collectors.toList());
            // 单词总数
            wordCount = words.size();
            vo.setWordsMissionNum(process.getCourseWordsMissionNum());
        } else if (process.getBookId() != null) {
            // 获取词书词汇卡片信息

            // 获取关联单词
            List<WordRelation> relations = wordRelationService.list(new LambdaQueryWrapper<WordRelation>().eq(WordRelation::getBelongId, process.getBookId()));
            // 获取单词数据
            List<EduWordLibrary> wordLibraries = new ArrayList<>();
            if (!relations.isEmpty()) {
                wordLibraries = eduWordService.listByIds(relations.stream().map(WordRelation::getWordId).collect(Collectors.toList()));
            }
            // 单词转MAP
            Map<String, EduWordLibrary> eduWordLibraryMap = wordLibraries.stream().collect(Collectors.toMap(EduWordLibrary::getId, i -> i));

            words = learnWords.stream().filter(i -> eduWordLibraryMap.containsKey(i.getWordId())).collect(Collectors.toList());

            // 获取词书数据
            book = wordBookService.selectWordBookById(process.getBookId());
            // 单词总数
            wordCount = wordLibraries.size();
            vo.setWordsMissionNum(process.getLevelWordsMissionNum());
        }

        // 筛选所有已完成和今日已完成
        for (EduWordLearnNew word : words) {
            // 今日已完成
            if (word.getKoDate() != null && DateUtil.formatDate(word.getKoDate()).equals(DateUtil.formatDate(date))) today++;
            // 总完成
            if (word.getKo().equals(1)) total++;
        }

        vo.setSource(source.charAt(0));
        vo.setName(source.equals("1") ? "课程词汇" : book.getBookName());
        if (source.equals("2")) {
            vo.setBookImg(book.getBookImg());
            vo.setBookOrCourseId(String.valueOf(book.getId()));
        }
        vo.setWordCount(wordCount);
        vo.setTotalWordsMissionCompletedNum(total);
        vo.setTodayWordsMissionCompletedNum(today);

        return vo;
    }


}
